<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>原生JS写tab切换</title>
    <style type="text/css">
        *{
            margin:0;
            padding: 0;
        }
        ul{
            list-style: none;
            float: left;
        }
        li{
            width: 100px;
            border: 2px solid #ccc;
            text-align: center;
            margin-top: -2px;
            height: 50px;
            line-height: 50px;
            cursor: pointer;
        }
        .tab{
            float: left;
            width: 300px;
            height: 204px;
            border: 2px solid #ececec;
            display: none;
            margin-left: 102px;
            text-align: center;
            line-height: 200px;
        }
        .hover{
            background-color: red;
            color: #fff;
        }
    </style>
</head>
<body>
<div class="tab" style="display:block;">第一部分</div>
<div class="tab">第二部分</div>
<div class="tab">第三部分</div>
<div class="tab">第四部分</div>
<ul>
    <li class="hover">标题1</li>
    <li>标题2</li>
    <li>标题3</li>
    <li>标题4</li>
</ul>
<script type="text/javascript">
    var lis = document.getElementsByTagName("li");
    var divs = document.getElementsByTagName("div");
    for(var i=0; i<lis.length; i++){
        //循环把i的值赋值给li的index
        lis[i].index = i;
        lis[i].onmouseover = function(){
            //移除每个li上存在的类
            for(var j=0; j<lis.length; j++){
                lis[j].className = "";
            }
            //给当前li添加类
            this.className ="hover";
            //隐藏每个div
            for(var i=0; i<divs.length; i++){
                divs[i].style.display="none";
            }
            //根据索引显示相应的div
            divs[this.index].style.display = "block";
        }
    }
</script>
</body>
</html>